package org.summerframework.web.filter;


import org.summerframework.web.exception.FilterFailureHandler;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石超
 * @version v1.0.0
 */
public interface BaseFilter extends Filter {
    @Override
    default void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    default void destroy() {

    }

    default FilterFailureHandler getFilterFailureHandler() {
        return new FilterFailureHandler();
    }

    default void onFilter(HttpServletRequest request, HttpServletResponse response) {

    }

    default void failure(HttpServletRequest request, HttpServletResponse response, Exception authException) {
        FilterFailureHandler filterFailureHandler = getFilterFailureHandler();

        if (filterFailureHandler != null) {
            filterFailureHandler.failure(request, response, authException);
        }
    }


    default void failure(ServletRequest request, ServletResponse response, Exception authException) {
        FilterFailureHandler filterFailureHandler = getFilterFailureHandler();

        if (filterFailureHandler != null) {
            filterFailureHandler.failure((HttpServletRequest) request, (HttpServletResponse) response, authException);
        }
    }

    @Override
    default void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            onFilter((HttpServletRequest) request, (HttpServletResponse) response);
            chain.doFilter(request, response);
        } catch (Exception e) {
            failure(request, response, e);
        }
    }
}
